﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.NewsLetters.Models;
using ERPStore.Extensions;

namespace ERPStore.NewsLetters.Services
{
	public class DBContactRecipientSourceProvider : IEmailListSourceProvider
	{
		private ERPStore.Models.UserListFilter m_Filter;

		public DBContactRecipientSourceProvider(ERPStore.Services.IAccountService accountService
			, ERPStore.Services.IValidatorService validator
			, NewsLettersService newsLetterService)
		{
			this.AccountService = accountService;
			this.ValidatorService = validator;
			this.NewsLetterService = newsLetterService;
		}

		protected ERPStore.Services.IAccountService AccountService { get; private set; }
		protected ERPStore.Services.IValidatorService ValidatorService { get; private set; }
		protected NewsLettersService NewsLetterService { get; private set; }

		#region IRecipientListProvider Members

		public void Initialize(Models.EmailListSource source)
		{
			if (source == null)
			{
				throw new ArgumentException("source does not be null");
			}
			if (source.Settings.IsNullOrEmpty())
			{
				m_Filter = new ERPStore.Models.UserListFilter();
			}
			else
			{
				var serializer = new System.Xml.Serialization.XmlSerializer(typeof(ERPStore.Models.UserListFilter));
				var buffer = System.Text.Encoding.UTF8.GetBytes(source.Settings);
				using (var ms = new System.IO.MemoryStream(buffer))
				{
					m_Filter = (ERPStore.Models.UserListFilter)serializer.Deserialize(ms);
					ms.Flush();
					ms.Close();
				}
			}
		}

		public IEnumerable<Models.EmailRecipient> GetList(int pageIndex, int pageSize, out int count)
		{
			count = 0;
			if (m_Filter == null)
			{
				return null;
			}
			var result = new List<Models.EmailRecipient>();
			var list = AccountService.GetUserListByFilter(m_Filter, pageIndex, pageSize, out count);
			foreach (var item in list)
			{
				var rcp = NewsLetterService.GetEmailRecipientByEmail(item.Email);
				if (rcp == null)
				{
					rcp = AutoMapper.Mapper.Map<Models.EmailRecipient>(item);
				}
				else
				{
					rcp = AutoMapper.Mapper.Map<ERPStore.Models.User, Models.EmailRecipient>(item, rcp);
				}
				NewsLetterService.SaveEmailRecipient(rcp);
				if (!rcp.IsBlackListed)
				{
					result.Add(rcp);
				}
			}

			return result;
		}

		public string SourceTypeId
		{
			get { return "FADC0FCB-488A-448B-8AC1-96FB986AF6D8"; }
		}

		public string DisplayName
		{
			get
			{
				return "Selection de contacts";
			}
		}

		public IList<ERPStore.Models.BrokenRule> Validate()
		{
			return ValidatorService.Validate(this.m_Filter);
		}

		public string GetSerializedSettings()
		{
			return m_Filter.SerializeToXml();
		}
		#endregion
	}
}
